package com.frontier.gateway8000.exception;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.frontier.common.BaseResponse;
import com.frontier.exception.CustomException;
import com.frontier.gateway8000.enumeration.ExceptionEnum;
import com.frontier.utils.BaseResponseUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 *网关异常处理器
 *
 * @author YLS-XuXu
 * @date 2022/3/2
 */
@Order(-1)
@Slf4j
@Component
@RequiredArgsConstructor
public class GatewayExceptionHandler implements WebExceptionHandler {


   /**
    * 网关全局异常处理器
    *
    * @param serverWebExchange
    * @param ex 异常内容
    * @return reactor.core.publisher.Mono<java.lang.Void>
    */
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable ex) {
        log.info("网关捕获到异常，异常信息：{}",ex);
        return getGateWayExceptionResponseMono(serverWebExchange,handleException(ex));
    }

   /**
    * 根据报错类型返回相应的返回值
    *
    * @param ex 报错类型
    * @return com.frontier.common.BaseResponse<T>
    */
    private BaseResponse handleException(Throwable ex){
        BaseResponse baseResponse;
        //服务未找到异常
        if(ex instanceof NotFoundException || ex instanceof ResponseStatusException){
            baseResponse= BaseResponseUtil.fail(ExceptionEnum.SYSTEM_NOT_FOUND_ERROR);
        }else if (ex instanceof CustomException){
            baseResponse=BaseResponseUtil.fail(((CustomException) ex).getErrorCode(),ex.getMessage());
        }else{
            baseResponse=BaseResponseUtil.fail(ExceptionEnum.SYSTEM_INNER_ERROR);
        }
        return baseResponse;
    }

   /**
    * 统一返回响应体
    *
    * @param serverWebExchange
    * @param  response
    * @return reactor.core.publisher.Mono<java.lang.Void>
    */
    private Mono<Void> getGateWayExceptionResponseMono(ServerWebExchange serverWebExchange, BaseResponse response){
        ServerHttpResponse httpResponse = serverWebExchange.getResponse();
        //设置响应编码为UTF-8
        httpResponse.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        //相应信息字节数组
        byte[] responseBytes = JSONUtil.toJsonStr(response).getBytes(StandardCharsets.UTF_8);
        //将相应信息数据返回
        return httpResponse.writeWith(Mono.just(httpResponse.bufferFactory().wrap(responseBytes)));
    }
}
